そこで、Nullable型の実体は構造体でしかないということに気づき、ならばNeverNullable構造体をC# 2.0で書けるか……と思って軽く試作してみました。
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication77
{
public struct NeverNullable<T>
{
T m_value;
public NeverNullable(T value)
{
if (value == null)
{
throw new NullReferenceException();
}
m_value = value;
}
public static implicit operator NeverNullable<T>( T value )
{
if (value == null)
{
throw new NullReferenceException();
}
return new NeverNullable<T>(value);
}
public static explicit operator T(NeverNullable<T> value)
{
return value.m_value;
}
}
class Program
{
static void Main(string[] args)
{
NeverNullable<string> a = new NeverNullable<string>("test1");
Console.WriteLine(a); // (※)そのまま使うと文字列は出力されない
Console.WriteLine((string)a); // キャストすれば文字列扱いにできる
a = "test2"; // 文字列オブジェクトへの入れ替えは可能
Console.WriteLine((string)a);
try
{
a = null; // nullへの置き換えは不可能。例外を投げる
}
catch (NullReferenceException)
{
Console.WriteLine("nullは代入できません!");
}
// 次のコード、なんとnull値を持つオブジェクトができてしまいます
NeverNullable<string> b = new NeverNullable<string>();
Console.WriteLine((string)b == null);
}
}
}